package com.example.clienteclinicav2;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.google.gson.JsonObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class BuquedaPacientePrestacionesActivity extends ListActivity{

	private EditText diagnosticoEditText;
	private EditText prestacionEditText;
	private TextView rutTextView;
	
	private static ArrayList<Node>mArray = new ArrayList<BuquedaPacientePrestacionesActivity.Node>();
	private MyAdapter mAdapter = null;
	
	private String NAMESPACE = "http://capaservicio";
	private String URL = "http://192.168.0.12:8080/ServicioPrestacionesClinica/services/RegistroORM";
	
	public class Node{
		public String descPrestacion;
		public String diagnostico;
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_busqueda_paciente_prestaciones);
      //  diagnosticoEditText = (EditText) findViewById(R.id.txtDiagnostico);
        rutTextView = (EditText) findViewById(R.id.editTextRut);
       // prestacionEditText = (EditText) findViewById(R.id.txtPrestacion);
        
	}
	
	public void carga()
	{
		mAdapter = new MyAdapter(this);
        this.setListAdapter(mAdapter);
	}
	
	public void buscar(View v)
	{
		JsonObject jsonObjectPelicula = new JsonObject();
		String rut = rutTextView.getText().toString();
		jsonObjectPelicula.addProperty("rut",rut);
		new BusquedaPacienteBackground().execute(jsonObjectPelicula.toString());
	}
	public class MyAdapter extends BaseAdapter
	{

		private Context mContext;
		
		public MyAdapter(Context c){
			Log.i("adapter", "cargando contexto");
			mContext = c;
		}
		public int getCount() {
			// TODO Auto-generated method stub
			return mArray.size();
		}
		public Object getItem(int posicion) {
			// TODO Auto-generated method stub
			return mArray.get(posicion);
		}
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = null;
			
			if(convertView==null){
				//Log.i("adapter", "null view");
				LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.activity_busqueda_paciente_prestaciones, null);
			}else{
				Log.i("adapter", "view");
				view = convertView;	
			}
			Log.i("adapter", "Cargando listado");
			TextView prestacion = (TextView) view.findViewById(R.id.txtPrestacion);
			prestacion.setText(mArray.get(position).descPrestacion);
			
			TextView diagnostico = (TextView) view.findViewById(R.id.txtDiagnostico);
			diagnostico.setText(mArray.get(position).diagnostico);
			
			return view;
		}
		
	}	

class BusquedaPacienteBackground extends AsyncTask<String, Void, String>{
		
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
    		progressDialog = ProgressDialog.show(
    				BuquedaPacientePrestacionesActivity.this,
    				"Prescli procesando la busqueda", 
    				"Espere mientras se buscan registro(s)...", 
    				true);
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(String... params) {

			String resultado = new String();
			String METHOD_NAME = "buscarPacienteVinculado";
			String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			request.addProperty("contenidoJson", params[0]);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				resultado = resultString.toString();

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return resultado;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			if("".equals(result)){
				Toast.makeText(BuquedaPacientePrestacionesActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}else{
				try {
					Log.i("mensaje", "llego al onpost");
					JSONArray peliculasJSONArray = new JSONArray(result);
					int cantPeliculas = peliculasJSONArray.length();
					for(int i = 0; i< cantPeliculas; i ++){
							Node mynode = new Node();
							mynode.descPrestacion  = peliculasJSONArray.getJSONObject(i).getString("descripPrestacion");
							mynode.diagnostico = peliculasJSONArray.getJSONObject(i).getString("diagnostico");
							mArray.add(mynode);
					}
					carga();
				} catch (JSONException e) {
					Toast.makeText(BuquedaPacientePrestacionesActivity.this, "2.Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
				}
			}
		}
	}
}
